<template>
  <a-modal
    :title="title"
    :width="800"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleOk"
    :bodyStyle="bodyStyle"
    @cancel="handleCancel"
    cancelText="关闭"
    wrapClassName="ant-modal-cust-warp"
    style="top:15%;height: 70%;overflow-y: scoll"
  >
    <template slot="footer">
      <a-button key="back" v-if="isReadOnly" @click="handleCancel">
        关闭
      </a-button>
      <a-button key="submit" type="primary" v-if="isReadOnly" @click="handleOk">
        关闭
      </a-button>
    </template>
    <a-spin :spinning="confirmLoading">
      <a-form :form="form" id="customerModal">
        <!-- <a-col :span="24 / 2">
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="业务负责人">
            <a-select
              :disabled="disableSubmit"
              v-decorator.trim="['applicant']"
              allowClear
              placeholder="选择业务负责人"
              showSearch
              optionFilterProp="children"
            >
              <a-select-option v-for="(item, index) in personList" :key="index" :value="item.id">
                {{ item.name }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col> -->
        <a-col :span="24 / 2">
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="内部编码">
            <a-input :disabled="disableSubmit" placeholder="请输入内部编码" v-decorator.trim="['contractCode']" />
          </a-form-item>
        </a-col>
        <a-col :span="24 / 2">
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="客户名称">
            <a-input :disabled="disableSubmit" placeholder="请输入客户名称" v-decorator.trim="['customerName']" />
          </a-form-item>
        </a-col>
        <!-- <a-col :span="24 / 2">
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="发货说明">
            <a-input :disabled="disableSubmit" placeholder="请输入发货条件" v-decorator.trim="['shippingRemark']" />
          </a-form-item>
        </a-col> -->
        <a-col :span="24 / 2">
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="发货日期">
            <a-input :disabled="disableSubmit" placeholder="请输入发货日期" v-decorator.trim="['shippingDate']" />
          </a-form-item>
        </a-col>
        <a-col :span="24 / 2">
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="是否符合发货条件">
            <a-select
              v-decorator.trim="['isSendable']"
              allowClear
              disabled
              placeholder="选择"
              showSearch
              @change="handleChange"
              optionFilterProp="children"
            >
              <a-select-option v-for="(item, index) in FList" :key="index" :value="item.id">
                {{ item.name }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="24 / 2" v-if="this.model.isSendable == 1">
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="不符合说明">
            <a-input disabled placeholder="请输入" v-decorator.trim="['notSendableDesc']" />
          </a-form-item>
        </a-col>
        <a-col :span="24 / 2">
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="上传">
            <a-upload
              name="file"
              :multiple="false"
              accept=".txt,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.pdf"
              :beforeUpload="beforeUpload"
              :headers="tokenHeader"
              :action="importExcelUrl"
              :showUploadList="false"
              v-decorator.trim="['unqualifiedImg']"
              @change="myhandleImportExcel"
            >
              <a-button> <a-icon type="upload" />上传</a-button>
            </a-upload>
          </a-form-item>
        </a-col>
        <a-col :span="24 / 2">
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="状态">
            <a-select
              :disabled="this.model.status !== 0"
              v-decorator.trim="['status']"
              allowClear
              placeholder="选择状态"
              showSearch
              optionFilterProp="children"
            >
              <a-select-option v-for="(item, index) in statusList" :key="index" :value="item.id">
                {{ item.name }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
      </a-form>
    </a-spin>
  </a-modal>
</template>
<script>
import pick from 'lodash.pick'
import { sendAudit, personList } from '@/api/api'
import { downFile, getAction } from '@/api/manage'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import { autoJumpNextInput } from '@/utils/util'
export default {
  name: 'SeeCustomerModal',
  mixins: [JeecgListMixin],
  data() {
    return {
      title: '操作',
      visible: false,
      disableSubmit: false,
      model: {},
      info: {},
      FList: [
        { id: 1, name: '否' },
        { id: 0, name: '是' }
      ],
      statusList: [
        {
          id: 1,
          name: '审批通过'
        },
        {
          id: 0,
          name: '待审批'
        },
        {
          id: 2,
          name: '驳回'
        }
      ],
      bodyStyle: {
        padding: '20',
        height: window.innerHeight * 0.7 + 'px',
        'overflow-y': 'auto'
      },
      personList: [],
      isReadOnly: true,
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      confirmLoading: false,
      defaultFileList: null,
      form: this.$form.createForm(this),
      url: {
        importExcelUrl: '/systemConfig/upload' + '?' + `biz=ht`,
        exportXlsUrl: '/systemConfig/static'
      },
      validatorRules: {
        name: {
          rules: [{ required: true, message: '请输入名称!' }]
        }
      }
    }
  },
  computed: {
    importExcelUrl: function() {
      return `${window._CONFIG['domianURL']}${this.url.importExcelUrl}`
      // return `api${this.url.importExcelUrl}`
    }
  },
  mounted() {
    personList().then(res => {
      if (res.code == 200 || res.code == 10000) {
        this.personList = res.data
      } else {
        this.$message.warning(res.message)
      }
    })
  },
  methods: {
    //图片上传前做限制
    beforeUpload(file) {
      return new Promise((resolve, reject) => {
        //文件名后缀
        let hz = file.name.substring(file.name.lastIndexOf('.'))
        let isType = ['.xlsx', '.doc', '.txt', '.docx', '.xls', '.ppt', '.pptx', '.pdf'].includes(hz)
        if (!isType) {
          this.$message.error('格式错误,只能上传.xlsx、.doc、.txt、.docx、.xls、.ppt、.pptx、.pdf')
          return reject(false)
        }
        return resolve(true)
      })
    },
    //选中为不符合
    handleChange(value) {
      if (value == '1') {
        this.state = true
      } else {
        this.state = false
      }
    },
    async getInfo(record) {
      let params = {
        approvalId: record.id
      }
      await getAction('/shippingyApprovalForm/getByApprovalId', params).then(res => {
        if (res.code !== 10000) {
          this.$message.warning(res.message)
          return
        }
        this.visible = true
        this.info = {}
        this.info = res.data
        if (this.info) {
          console.log('info', this.info)
          this.model = Object.assign({}, this.info, { status: record.status })
          this.model.id = record.id
        }
        console.log('model', this.model)
        console.log('info1', this.info)
      })
    },
    myhandleExportXls(fileName) {
      if (!fileName || typeof fileName != 'string') {
        fileName = '导出文件'
      }
      downFile(this.url.exportXlsUrl + '/' + this.model.approvalForm).then(data => {
        if (!data) {
          this.$message.warning('文件下载失败')
          return
        }
        if (typeof window.navigator.msSaveBlob !== 'undefined') {
          window.navigator.msSaveBlob(new Blob([data], { type: 'application/vnd.ms-excel' }), fileName + '.xls')
        } else {
          let url = window.URL.createObjectURL(new Blob([data], { type: 'application/vnd.ms-excel' }))
          let link = document.createElement('a')
          link.style.display = 'none'
          link.href = url
          link.setAttribute('download', fileName + '.xls')
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link) //下载完成移除元素
          window.URL.revokeObjectURL(url) //释放掉blob对象
        }
      })
    },
    /* 导入 */
    myhandleImportExcel(info) {
      if (info.file.status !== 'uploading') {
        console.log(info.file, info.fileList)
      }
      if (info.file.status === 'done') {
        if (info.file.response) {
          // this.$message.success(`${info.file.name} 文件上传成功`);
          if (info.file.response.code === 200 || info.file.response.code === 10000) {
            this.$message.success(`${info.file.name} 文件上传成功` || info.file.response.data)
            this.defaultFileList = info.file.response.data
            console.log('defaultFileList:', this.defaultFileList)
          } else {
            this.$message.warning(info.file.response.message)
          }
        } else {
          this.$message.error(`${info.file.name} ${info.file.response.data}.`)
        }
      } else if (info.file.status === 'error') {
        this.$message.error(`文件上传失败: ${info.file.msg} `)
      }
    },
    add() {
      this.edit()
    },
    edit(record) {
      //通过id查询填表内容
      this.getInfo(record)
      this.form.resetFields()
      this.$nextTick(() => {
        setTimeout(() => {
          console.log(this.model, 'xxxxx')
          this.form.setFieldsValue(
            pick(
              this.model,
              'notSendableDesc',
              'status',
              'customerName',
              'contractCode',
              'isSendable',
              // 'applicant',
              'contractNum',
              'shippingDate'
              // 'shippingRemark'
            )
          )
          autoJumpNextInput('customerModal')
        }, 500)
      })
    },
    close() {
      this.$emit('close')
      this.visible = false
      this.isReadOnly = true
    },
    handleOk() {
      const that = this
      // 触发表单验证
      this.form.validateFields((err, values) => {
        if (!err) {
          that.confirmLoading = true
          let formData = Object.assign(this.model, values)
          if (this.model.beginNeedGet && this.model.beginNeedPay) {
            that.$message.warn('期初应收和期初应付不能同时输入')
            that.confirmLoading = false
            return
          }
          formData.id = this.model.id
          formData.approvalForm = this.defaultFileList
          formData.stage = 1
          let obj
          if (!this.model.id) {
            obj = sendAudit(formData)
          } else {
            obj = sendAudit(formData)
          }
          obj
            .then(res => {
              if (res.code === 200 || res.code === 10000) {
                this.$message.success('保存成功')
                that.$emit('ok')
              } else {
                that.$message.warning(res.data.message)
              }
            })
            .finally(() => {
              that.confirmLoading = false
              that.close()
            })
        }
      })
    },
    handleCancel() {
      this.close()
    },
    validateSupplierName(rule, value, callback) {
      let params = {
        name: value,
        type: '客户',
        id: this.model.id ? this.model.id : 0
      }
      checkSupplier(params).then(res => {
        if (res && res.code === 200) {
          if (!res.data.status) {
            callback()
          } else {
            callback('名称已经存在')
          }
        } else {
          callback(res.data)
        }
      })
    }
  }
}
</script>
<style scoped></style>
